﻿$(function () {
    //layui预览图片
    // layui.use('layer', function () {
    //     var $ = layui.$
    //         , layer = layui.layer //弹层
    // });
    
    $('#find').click(function () {
    	selectPage(1);
    	//$('#list').show();
    });

    $('#add').click(function () {
        window.open("/Odreceipt/addStoreOdreceiptView")
    });

    //初始化下拉框
    function init() {

        $.ajax({
            type: "post",
            data:{},
            url:"/Odreceipt/listOdarea/",
            dataType: "json",
            success: function(data) {
                // var res = eval("(" + data + ")");
                for (let i=0; i< data.result.length; i++) {
                    $("#area").append("<option value='"+data.result[i].area+"'>"+data.result[i].area+"</option>");
                }
            },
        });

    }
    //初始化区域选择框
    init();
    
    function selectPage(pageCode) {
    	
    	var startDate = $('#startDate').val();
    	var endDate = $('#endDate').val();
        var name = $('#name').val();
    	var options = $("#area option:selected");
    	var area = options.val();

    	if(startDate===""||startDate==null){
    		
//    		$('body').alert({
//    		type: 'warning',
//    		content:'开始日期不能为空!'
//    		});
//    		return;
			swal("开始时间不能为空!");
			return;

    	}
    	if(endDate===""||endDate==null){
    		
//    		$('body').alert({
//    		type: 'warning',
//    		content:'结束日期不能为空!'
//    		});
//    		return;
			swal("结束时间不能为空!");
			return;
    	}
    	

        //分页查询 pageCode：页数
        $.ajax({
			type : "post",
			url : "/Odreceipt/listStoreOdreceipt",
			data:{"startDate":startDate,"endDate":endDate,"name":name,"area":area},
			dataType : "json",
			success : function(data) {
//				var bill_objRecords = eval("(" + redata.result + ")");
//				maxItems = eval("(" + redata.count + ")");
				$("#detail").html("");
				$("#detail #data").html("");
                //总页数
                $("#countPage").text(data.totalPage);
                $("#totalCount").text(data.totalCount);
//				for (var i = 0; i < data.result.length; i++) {
//
//                    $("#detail").append(
//                        "<tr>\n" +
//                        "<td>"+data.result[i].ticketno+"</td>\n" +
//                        "<td>"+data.result[i].carno+"</td>\n" +
//                        //"<td>"+dateFormat(data.result[i].grosstime,"")+"</td>\n" +
//                        "<td>"+data.result[i].grosstime+"</td>\n" +
//                        "<td>"+data.result[i].netweight+"</td>\n" +
//                        "<td>"+data.result[i].productname+"</td>\n" +
//                        "<td>"+data.result[i].username+"</td>\n" +
//                        "<td>"+data.result[i].iccode+"</td>\n" +
//                        "</tr>"
//                    );
//				}
                if(data.result.length<=0){
                    $('#datatable-buttons').dataTable().fnClearTable();
                	swal("查询失败！", "未查询到满足条件的结果！");
                }
                else{
                	
    				$('#datatable-buttons').dataTable().fnClearTable();
    				$('#datatable-buttons').dataTable().fnAddData(packagingdatatabledata(data),true);
                    $('#datatable-buttons').dataTable().fnSort([[4, 'desc']]);

                }


			}
		});
        
        
    }
   
   function packagingdatatabledata(data){
   
	   var a=[]; //全部行数据的list
	   var banddata = data.result;
	   for(var key in banddata){
	     var tempObj=[];  //一行数据的list
	     tempObj.push(banddata[key].name);
	     tempObj.push(banddata[key].area);
	     tempObj.push(banddata[key].weight);
	     tempObj.push(dateFormat(banddata[key].smdate,"y-m-d"));
	     tempObj.push(dateFormat(banddata[key].createdate,"y-m-d"));
	     if(banddata[key].state===1){
             tempObj.push('<span class="label label-success" style="font-size: 100%;display:table;margin-left: auto;margin-right: auto;">已收</span>');
         }
	     else{
             tempObj.push('<span class="label label-danger" style="font-size: 100%;display:table;margin-left: auto;margin-right: auto;">未收</span>');
         }
	     tempObj.push(banddata[key].remark);
//	     var actionHtml='<input data-id ="'+banddata[key].id+'" class="btn btn-danger waves-effect waves-light" style="display: table;width: auto;margin-left: auto;margin-right: auto" id="update" type="button" value="修改"/>';
	     //var actionHtml='<input data-id ="'+banddata[key].id+'" class="btn btn-danger waves-effect waves-light m-l-10" id="approve" value="'+approvevalue+'" type="button"/>';
         //actionHtml+='<input data-id ="'+banddata[key].fname+'" class="btn btn-info waves-effect waves-light m-l-10" id="viewattach" value="查看附件" type="button"/>';
         // actionHtml+='<input data-id ="'+banddata[key].id+'" class="btn btn-info waves-effect waves-light m-l-10" id="downloadword" value="下载合同" type="button"/>';
         // var editHtml='<button id="approve" href="#modal-container-648308" rel="external nofollow" data-toggle="modal" data-id ="'+banddata[key].id+'" class="btn btn-xs btn-info"> <i class="icon-edit bigger-120"></i>审批</button> <button id="viewattach" href="#modal-container-648300" rel="external nofollow" data-toggle="modal" data-id ="'+banddata[key].fname+'" class="btn btn-xs btn-danger"> <i class="icon-trash bigger-120">查看附件</i> </button>';
//         tempObj.push(actionHtml);
	     //tempObj.push(editHtml);
	     a.push(tempObj);
	    }
 	   return a;
   }

   //月报导出到本地
    $('#monthlyExcelOutLocal').click(function () {

        var searchDate = $('#searchDate').val();
        if(searchDate===""||searchDate==null){
            swal("导出日期不能为空!");
            return;
        }
        $.ajax({
            type : "post",
            url : "/Odreceipt/monthlyExcelOutLocal",
            data:{"searchDate":searchDate},
            dataType : "json",
            success : function(data) {
/*                if(data.result===1){

                    swal("导出成功！", "文件已保存至桌面！");
                }
                else if(data.result===0){
                    swal("导出失败！", "当前文件正在被打开，请先关闭！");
                }
                else{
                    swal("导出失败！", "请重新尝试！");
                }*/


            }
        });
    });

    //月报导出到浏览器
    $('#monthlyExcelOutExplorer').click(function () {
        var searchDate = $('#searchDate').val();
        if(searchDate===""||searchDate==null){
            swal("导出日期不能为空!");
            return;
        }
        window.location.href = "/Odreceipt/monthlyExcelOutExplorer?searchDate="+searchDate
    });

   
   //修改
   $('#datatable-buttons')
	.on('click', '#update', function( e ) {

    	var id = $(this).attr("data-id");
    	$(this).parents().parents().children("td").eq(2).attr("contentEditable","true");
    	$(this).attr("style","display:none;");
    	$(this).parents().parents().children("td").eq(7).html("<input data-id='"+id+"' class='btn btn-success waves-effect waves-light m-l-10' style='display: table;width: auto;margin-left: auto;margin-right: auto' id='save' type='button' value='保存' />"+"\n"+"<input data-id='"+id+"' class='btn btn-info waves-effect waves-light' style='display: table;width: auto;margin-left: auto;margin-right: auto' id='cancel' type='button' value='取消' />"+"\n");

    	
    	
	})

	//取消
   $('#datatable-buttons').on('click', '#cancel', function( e ) {

	   	var id = $(this).attr("data-id");
		$(this).parents().parents().children("td").eq(2).attr("contentEditable","false");
		$(this).attr("style","display:block;");
		$(this).parents().parents().children("td").eq(7).html("<input data-id='"+id+"' class='btn btn-danger waves-effect waves-light' style='display: table;width: auto;margin-left: auto;margin-right: auto' id='update' type='button' value='修改' />"+"\n");

    	
    	
	})
	
	
	//保存
	$('#datatable-buttons').on('click', '#save', function( e ) {
		
		
		var weight = $(this).parents().parents().children("td").eq(2).text();
    	var id = $(this).attr("data-id");
        $.ajax({
			type : "post",
			url : "/Odreceipt/updateStoreOdreceipt",
			data:{"weight":weight,"id":id},
			dataType : "json",
			success : function(data) {

				if(data.result==true){
					
			        swal("保存成功!", "", "success");
			        
					$('#save').parents().parents().children("td").eq(2).attr("contentEditable","false");
					$('#save').parents().parents().children("td").eq(7).html("<input data-id='"+id+"' class='btn btn-danger waves-effect waves-light' style='display: table;width: auto;margin-left: auto;margin-right: auto' id='update' type='button' value='修改' />"+"\n");

				}
				else{
					
					swal("保存失败！", "请检查输入数据格式！"); 

				}

			}
		});
    	
    	
	})

    //审批
    $('#datatable-buttons').on('click', '#approve', function( e ) {

        var approvestate = $(this).parents().parents().children("td").eq(7).text();
        var id = $(this).attr("data-id");
        $.ajax({
            type : "post",
            url : "/Contract/approveContract",
            data:{"id":id,"approvestate":approvestate},
            dataType : "json",
            success : function(data) {

                if(data.result==true){

                    // swal("审批成功!", ="", "success");
                    if(approvestate==="未审批"){
                        swal({title: "审批成功!",text: "",button: "确定"},
                            function(){
                                selectPage();
                            }
                        );
                    }else{
                        swal({title: "取消审批成功!",text: "",button: "确定"},
                            function(){
                                selectPage();
                            }
                        );
                    }

                    // $('#save').parents().parents().children("td").eq(7).attr("contentEditable","false");
                    // $('#save').parents().parents().children("td").eq(11).html("<input data-id='"+id+"' class='btn' id='approve' type='button' value='取消审批' />"+"\n");

                }
                else{

                    swal("审批失败！", "请重新审批！");

                }

            }
        });
    })

    //查看附件
    $('#datatable-buttons').on('click', '#viewattach', function( e ) {
        var fname = $(this).attr("data-id");
        if(fname===null||fname===""||fname==="undefined"||fileExists(fname)===false){
            swal("预览失败！", "未上传附件或文件已损坏！");
        }else{
            previewPicture(fname);
        }

    })
    //下载word
    $('#datatable-buttons').on('click', '#downloadword', function( e ) {
        var id = $(this).attr("data-id");
        $.ajax({
            type : "post",
            url : "/Contract/contractWordOut",
            data:{"id":id},
            dataType : "json",
            success : function(data) {
                if(data.result==1){

                    swal("导出成功！", "合同已保存至桌面！");
                }
                else if(data.result==0){
                    swal("导出失败！", "当前文件正在被打开，请先关闭！");
                }
                else{
                    swal("导出失败！", "请重新尝试！");
                }


            }
        });

    })
    /**
     * 日期格式化
     * @param Number time 时间戳
     * @param String format 格式
     */
    function dateFormat (time, format) {
      const t = new Date(time)
      // 日期格式
      format = format || 'Y-m-d h:i:s'
      let year = t.getFullYear()
      // 由于 getMonth 返回值会比正常月份小 1
      let month = t.getMonth() + 1
      let day = t.getDate()
      let hours = t.getHours()
      let minutes = t.getMinutes()
      let seconds = t.getSeconds()

      const hash = {
        'y': year,
        'm': month,
        'd': day,
        'h': hours,
        'i': minutes,
        's': seconds
      }
      // 是否补 0
      const isAddZero = (o) => {
        return /M|D|H|I|S/.test(o)
      }
      return format.replace(/\w/g, o => {
        let rt = hash[o.toLocaleLowerCase()]
        return rt >= 10 || isAddZero(o) ? rt : `0${rt}`
      })
    }

    //layui预览图片
    //图片预览，传url
    function previewPicture(url) {
        layer.photos({
            photos: {
                "title": '预览图',
                "id": 222,
                "start": 0,
                "data": [{
                    "src": url
                }]
            }
            ,closeBtn: 1 //是否显示关闭按钮
        });
    }

    function fileExists(url) {
        var isExists;
        $.ajax({
            url: url,
            async: false,
            type: 'HEAD',
            error: function () {
                isExists = 0;
            },
            success: function () {
                isExists = 1;
            }
        });
        if (isExists == 1) {
            return true;
        } else {
            return false;
        }
    }


})